package com.xywh.dakaqiandao.mvp.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dds.soap.SoapListener;
import com.dds.soap.SoapParams;
import com.dds.soap.SoapUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xywh.dakaqiandao.R;
import com.xywh.dakaqiandao.di.component.DaggerDiQuSheZhiComponent;
import com.xywh.dakaqiandao.di.module.DiQuSheZhiModule;
import com.xywh.dakaqiandao.mvp.contract.DiQuSheZhiContract;
import com.xywh.dakaqiandao.mvp.presenter.DiQuSheZhiPresenter;
import com.xywh.dakaqiandao.mvp.ui.adapter.DiQuSheZhiAdapter;
import com.xywh.dakaqiandao.mvp.ui.entity.DiQuSheZhi;

import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import me.jessyan.armscomponent.commonres.view.RecycleViewDivider;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;
import me.jessyan.armscomponent.commonsdk.utils.Utils;

import static com.jess.arms.base.BaseConstants.BASE_URL;
import static com.jess.arms.base.BaseConstants.NAME_SPACE;
import static com.jess.arms.utils.Preconditions.checkNotNull;


@Route(path = RouterHub.ACTIVITY_DI_QU_SHE_ZHI)
public class DiQuSheZhiActivity extends BaseActivity<DiQuSheZhiPresenter> implements DiQuSheZhiContract.View, OnRefreshListener, DiQuSheZhiAdapter.DiQuHashMap {


    private static boolean mIsNeedDemo = true;
    @BindView(R.id.empty_text)
    TextView empty_text;
    @BindView(R.id.empty_image)
    ImageView empty_image;

    @BindView(R.id.empty)
    View mEmptyLayout;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.refreshLayout)
    RefreshLayout mRefreshLayout;
    @BindView(R.id.btnRight)
    TextView mBtnRight;
    private DiQuSheZhiAdapter mAdapter;
    private List<DiQuSheZhi> mDataBeanList = new ArrayList<>();
    private HashMap<String, String> mQiQuData = new HashMap<>();
    private View.OnClickListener mRightListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            addUserRegionInfo();

        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mAdapter = null;
        mDataBeanList = null;
        mQiQuData = null;
        mRightListener = null;
    }

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerDiQuSheZhiComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .diQuSheZhiModule(new DiQuSheZhiModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_di_qu_she_zhi; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        ToolbarUtils.initToolbarTitleBack(this, getString(R.string.activity_di_qu_she_zhi));

        initRefreshLayout();
        initRecyclerView();
        initEmpty();
        mBtnRight.setText("确定");
        mBtnRight.setOnClickListener(mRightListener);
        getRegionList();
    }

    private void initRefreshLayout() {
        mRefreshLayout.setRefreshHeader(new
                ClassicsHeader(this).setSpinnerStyle(SpinnerStyle.FixedBehind).setPrimaryColorId(R.color.public_colorPrimary).setAccentColorId(android.R.color.white));
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.autoRefresh();
        mRefreshLayout.setEnableLoadMore(false);
    }

    private void initRecyclerView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(DiQuSheZhiActivity.this));
        mRecyclerView.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.VERTICAL, 10, Color.parseColor("#EEEEEE")));

//        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setAdapter(mAdapter = new DiQuSheZhiAdapter(DiQuSheZhiActivity.this, mDataBeanList, this));

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
            }
        });
    }

    private void initEmpty() {
        empty_image.setImageResource(R.drawable.ic_empty);
        empty_text.setTextColor(getResources().getColor(R.color.public_white));
        empty_text.setText("暂无数据");
    }


    private void getRegionList() {

        showLoading();

        String methodName = "getRegionList";

        SoapUtil soapUtil = SoapUtil.getInstance(this);
        soapUtil.setDotNet(true);
        SoapParams params = new SoapParams();
        params.put("identityCardNo", mSharedPreferencesHelper.getString(BaseConstants.USERNAME));


        /**
         * 请求
         */
        soapUtil.callEntry(BASE_URL, NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty("getRegionListResult").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("-1")) {
                    List<DiQuSheZhi> entityList = new Gson().fromJson(result, new TypeToken<List<DiQuSheZhi>>() {
                    }.getType());

                    if (entityList != null && entityList != null && entityList.size() > 0) {
                        mDataBeanList.clear();
                        mDataBeanList.addAll(entityList);

                        for (int i = 0; i < mDataBeanList.size(); i++) {
                            if (mDataBeanList.get(i).getCheckfFlg().equals("1")) {
                                mAdapter.map.put(i, true);// 默认所有的checkbox都是没选中
                            } else if (mDataBeanList.get(i).getCheckfFlg().equals("")) {
                                mAdapter.map.put(i, false);// 默认所有的checkbox都是没选中
                            }
                        }
                        mAdapter.notifyDataSetChanged();

                        mEmptyLayout.setVisibility(View.GONE);
                        mRecyclerView.setVisibility(View.VISIBLE);
                    } else {
                        mEmptyLayout.setVisibility(View.VISIBLE);
                        mRecyclerView.setVisibility(View.GONE);
                    }

                } else {
                    mEmptyLayout.setVisibility(View.VISIBLE);
                    mRecyclerView.setVisibility(View.GONE);

                }
            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        },getAapiUserName(),getApiPwd());


    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    /**
     * addUserRegionInfo(string employeeName, string identityCardNo, string regionName)
     */
    private void addUserRegionInfo() {


        String qiQUStrIds = "";
        String qiQUStrNames = "";
        for (Map.Entry<String, String> entry : mQiQuData.entrySet()) {
            qiQUStrNames += entry.getValue() + ",";
            qiQUStrIds += entry.getKey() + ",";
        }

        if (qiQUStrIds.length() > 0) {
            qiQUStrIds = ArmsUtils.cutLastString(qiQUStrIds);
            qiQUStrNames = ArmsUtils.cutLastString(qiQUStrNames);
        }

        if (qiQUStrIds.length() == 0) {
            ArmsUtils.makeText(getContext(), "至少选择一个地区");
            return;
        }

        showLoading();


        String methodName = "addUserRegionInfo";

        SoapUtil soapUtil = SoapUtil.getInstance(this);
        soapUtil.setDotNet(true);
        SoapParams params = new SoapParams();
        params.put("employeeName", mSharedPreferencesHelper.getString(BaseConstants.USERNAME));
        params.put("identityCardNo", mSharedPreferencesHelper.getString(BaseConstants.USERNAME));
        params.put("regionName", qiQUStrNames);
        params.put("regionId", qiQUStrIds);


        /**
         * 请求
         */
        soapUtil.callEntry(BASE_URL, NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty("addUserRegionInfoResult").toString();
                if (result != null && !result.equals("-1")) {
                    ArmsUtils.makeText(getContext(), "设置成功");
                    mSharedPreferencesHelper.putString(BaseConstants.IS_SET, "1");
                    Utils.navigation(getContext(), RouterHub.ACTIVITY_QIAN_DAO);
                    killMyself();

                } else {
                    ArmsUtils.makeText(getContext(), "设置失败");
                    mSharedPreferencesHelper.putString(BaseConstants.IS_SET, "0");
                }
            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        },getAapiUserName(),getApiPwd());


    }

    private List<DiQuSheZhi> loadModels() {
        List<DiQuSheZhi> lists = new ArrayList<>();

        for (int i = 0; i < 5; i++) {

            DiQuSheZhi dataBean = new DiQuSheZhi();
            lists.add(dataBean);
        }

        return lists;
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {

        //getDiQuSheZhiList();
        mRefreshLayout.finishRefresh();
        mEmptyLayout.setVisibility(View.GONE);

    }

    @Override
    public void getDiQuSheZhiDataSuccess(DiQuSheZhi entityList) {

//        if (entityList != null && entityList.getData() != null && entityList.getData().size() > 0) {
//            mDataBeanList.clear();
//            mDataBeanList.addAll(entityList.getData());
//            mAdapter.notifyDataSetChanged();
//            mEmptyLayout.setVisibility(View.GONE);
//        } else {
//            mEmptyLayout.setVisibility(View.VISIBLE);
//        }

    }

    private void getDiQuSheZhiList() {
        HashMap<String, String> map = new HashMap<>();

        mPresenter.getDiQuSheZhiList(map);
    }

    @Override
    public void addHashMapData(DiQuSheZhi diQuSheZhi) {
        mQiQuData.put(String.valueOf(diQuSheZhi.getRegionId()), diQuSheZhi.getRegionName());
    }

    @Override
    public void removeHashMapData(DiQuSheZhi diQuSheZhi) {

        if (mQiQuData.containsKey(String.valueOf(diQuSheZhi.getRegionId()))) {
            mQiQuData.remove(String.valueOf(diQuSheZhi.getRegionId()));
        }
    }
}
